<?php
namespace Admin\Controller;

use Admin\Controller\GlobalController;

class IssueController extends GlobalController
{
    //杂志列表
    public function getlist()
    {
        $pageSize = 20;
        $where = array();
        $issueModel = M('comic_issue');
        $count = $issueModel->where($where)->count();
        $pageObj = new \Admin\Util\Page($count, $pageSize);
        $list = $issueModel->where($where)->order('issue_id desc')->limit($pageObj->firstRow . ',' . $pageObj->listRows)->select();
        $eggModel = M('egg');
        foreach ($list as $key => $row) {
            $egg_num = $eggModel->where(array('issue_id' => $row['issue_id'], 'status' => 1))->count();
            $list[$key]['egg_num'] = $egg_num;
        }
        $this->assign('list', $list);
        $this->assign('page', $pageObj->show());
        $this->display();
    }

    //添加或者修改
    public function save()
    {
        $issueModel = M('comic_issue');
        if (IS_POST) {
            $issue_id = I('post.issue_id', 0, 'intval');
            $data['comic_id'] = I('post.comic_id', 0, 'intval');
            $data['issue_number'] = I('post.issue_number', 0, 'trim');
            $data['banner_img'] = I('post.banner_img', '', 'trim');
            $data['spoiler_id'] = I('post.spoiler_id', 0, 'intval');
            $data['description'] = I('post.description', '', 'trim');
            if ($issue_id) {
                $issueModel->where(array('issue_id' => $issue_id))->save($data);
            } else {
                $issueModel->add($data);
            }
            $this->ajaxReturn('', 'success', 'TIP_SUCCESS');
        }
        $issue_id = I('get.issue_id', 0, 'intval');
        $info = $issueModel->where(array('issue_id' => $issue_id))->find();
        if (!$info) {
            $comic_id = I('get.comic_id', 0, 'intval');
            $info = array('comic_id' => $comic_id);
        }

        $comicModel = M('comic');
        $list = $comicModel->select();
        $this->assign('list', $list);

        $this->assign('issue_id', $issue_id);
        $this->assign('info', $info);
        $this->display();
    }

    public function publish()
    {
        if (IS_POST) {
            $issue_id = I('post.issue_id', '', 'intval');
            $issueModel = M('comic_issue');
            $issueModel->where(array('issue_id' => $issue_id))->setField('status', array('exp', '1 - status'));
            $this->ajaxReturn('', 'success', 'TIP_SUCCESS');
        }
    }

    public function del()
    {
        $issue_id = I('post.issue_id', 0, 'intval');
        //杂志下已经有彩蛋不能删除
        $eggModel = M('egg');
        $rs = $eggModel->where(array('issue_id' => $issue_id, 'status' => 1))->find();
        if ($rs) {
            $this->ajaxReturn('', '期刊下有已上线的彩蛋不能删除', 'TIP_ERROR');
        }
        $issueModel = M('comic_issue');
        $issueModel->where(array('issue_id' => $issue_id))->delete();
        $this->ajaxReturn('', 'success', 'TIP_SUCCESS');
    }
}